using System.Collections.Generic;
using UnityEngine;
using PETimer;

/// <summary>
/// 定时器管理器 - 全局单例，用于在Unity主线程中统一更新所有需要主线程处理的定时器
/// 只有当定时器回调需要调用Unity API时才需要注册到这个管理器
/// 纯逻辑处理的定时器可以使用 setHandle=false，无需注册
/// </summary>
public class TimerUpdateComponent : MonoBehaviour
{
    private static TimerUpdateComponent m_Instance;
    public static TimerUpdateComponent Instance
    {
        get
        {
            if (m_Instance == null)
            {
                m_Instance = FindObjectOfType<TimerUpdateComponent>();
                if (m_Instance == null)
                {
                    GameObject go = new GameObject("TimerManager");
                    m_Instance = go.AddComponent<TimerUpdateComponent>();
                    DontDestroyOnLoad(go);
                }
            }
            return m_Instance;
        }
    }
    
    private List<TickTimer> m_Timers = new List<TickTimer>();
    private readonly object m_Lock = new object();
    
    private void Awake()
    {
        if (m_Instance == null)
        {
            m_Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else if (m_Instance != this)
        {
            Destroy(gameObject);
        }
    }
    
    /// <summary>
    /// 注册需要主线程更新的定时器（回调中需要调用Unity API的定时器）
    /// </summary>
    public void RegisterTimer(TickTimer timer)
    {
        if (timer == null) return;
        
        lock (m_Lock)
        {
            if (!m_Timers.Contains(timer))
            {
                m_Timers.Add(timer);
                Logger.Log("TimerManager", $"注册定时器: {timer.GetType().Name}");
            }
        }
    }
    
    /// <summary>
    /// 注销定时器
    /// </summary>
    public void UnregisterTimer(TickTimer timer)
    {
        if (timer == null) return;
        
        lock (m_Lock)
        {
            if (m_Timers.Remove(timer))
            {
                Logger.Log("TimerManager", $"注销定时器: {timer.GetType().Name}");
            }
        }
    }
    
    private void Update()
    {
        // 在Unity主线程中更新所有注册的定时器
        lock (m_Lock)
        {
            for (int i = m_Timers.Count - 1; i >= 0; i--)
            {
                var timer = m_Timers[i];
                if (timer != null)
                {
                    // 更新定时器任务
                    timer.UpdateTask();
                    
                    // 处理定时器回调（在主线程中执行）
                    timer.HandleTask();
                }
                else
                {
                    // 清理空引用
                    m_Timers.RemoveAt(i);
                }
            }
        }
    }
    
    private void OnDestroy()
    {
        lock (m_Lock)
        {
            m_Timers.Clear();
        }
        
        if (m_Instance == this)
        {
            m_Instance = null;
        }
    }
}

